/*
 * battery.c
 *
 *  Created on: Dec 4, 2023
 *      Author: boen
 */

#include <battery.h>

static uint16_t adc_value[2];

/**
* @brief
* @param
* @retval
*/
int battery_init(void)
{
	xbot.battery.design_capacity = 6;
	xbot.battery.power_supply_status = POWER_SUPPLY_STATUS_UNKNOWN;
	xbot.battery.power_supply_health = POWER_SUPPLY_HEALTH_GOOD;
	xbot.battery.power_supply_technology = POWER_SUPPLY_TECHNOLOGY_LION;
	xbot.battery.present = 1;
	return 0;
}

/**
* @brief
* @param
* @retval
*/
int battery_deinit(void)
{
	return 0;
}

/**
* @brief
* @param
* @retval
*/
void battery_polling(void)
{
	if(adc_value[0] != 0 && adc_value[0] != 4095) {
	    float volt = 1210.0f / ((float)adc_value[0]) * ((float)adc_value[1]) * 11.0f ; /* 1210.0是内部参考电压值， 100k + 10k 电阻分压， 实际电压是测量电压的11倍 */
        xbot.battery.voltage = volt/1000;
        if((xbot.battery.voltage>1)||(xbot.battery.voltage<=0))
		{
        	xbot.battery.voltage = 0;
        	xbot.battery.percentage = 0;
        	xbot.battery.present = 0;
        	xbot.battery.power_supply_health = POWER_SUPPLY_HEALTH_DEAD;
		}
        else
        {
        	xbot.battery.percentage = 1-(xbot.battery.voltage-MIN_BATTERY_VOLTAGE)/(MAX_BATTERY_VOLTAGE-MIN_BATTERY_VOLTAGE);
        }

    }

	//XDEBUG("battery: %0.1f[%0.2f%%]\r\n", xbot.battery.voltage, xbot.battery.percentage);
    HAL_ADC_Start_DMA(&ADC_PORT_PWR, (uint32_t*)adc_value, 2);
}
